package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.demo.common.Result;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * <p> @Title DemoController
 * <p> @Description 测试控制器
 *
 * @author tia.bin
 * @date 2021/11/5 9:34
 */
@RestController
@RequestMapping("/test")
public class DemoController {

    @GetMapping("/getFile")
    public void findIp(@RequestParam(value = "fileName", required = false) String fileName,
                         @RequestParam(value = "filePath", required = false) String filePath,
                         HttpServletResponse response) throws IOException {
        if (fileName == null || fileName.trim().length() == 0) {
            response.getWriter().write(JSON.toJSONString(Result.failed("fileName参数不能为空")));
            return;
        }
        if (filePath == null || filePath.trim().length() == 0) {
            response.getWriter().write(JSON.toJSONString(Result.failed("filePath参数不能为空")));
            return;
        }
        File file = new File(filePath);
        response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
        response.setHeader("Access-Control-Expose-Headers","Content-Disposition");
        IOUtils.copy(Files.newInputStream(file.toPath()), response.getOutputStream());
    }

}
